
"""
    操作日志
"""

from audit.serialiaers.operation import OperationModelSerializer
from audit.models import OperationModel
from utils.export import ExportExcel
from utils.json_response import JsonResponse
from utils.filter import DoctorsFilter
from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action


class OperationModelViewGet(ListModelMixin, GenericViewSet):
    """
    操作日志：查导
    """
    perms_map = ({'*': 'admin'}, {'*': 'operation_all'}, {'get': 'operation_list'}, {'export': 'operation_export'})
    queryset = OperationModel.objects.all()
    serializer_class = OperationModelSerializer
    search_fields = ('username', 'name', 'mobile', 'action', 'resource_type', 'resource', 'ip')  # 已在全局设置：指定字段模糊搜索
    filter_class = DoctorsFilter
    ordering_fields = ('time',)

    sheet = '操作日志'
    title = {
        'id': 'ID', 'username': '用户', 'name': '姓名', 'mobile': '手机号', 'action': '动作', 'resource_type': '资源类型',
        'resource': '资源', 'ip': 'IP地址', 'time': '日期'
    }

    @action(methods=['post'], detail=False)  # url 访问127.0.0.1:8080/api/方法名
    def export_all(self, request):
        """
        根据数据表导出Excel表
        """
        serializer = self.get_serializer(self.queryset, many=True)
        name = ExportExcel(serializer.data, self.sheet, self.title).write(serializer.data, self.sheet, self.title)
        operation(request, name, self.get_queryset().model._meta.verbose_name_plural, '导出所有')
        return JsonResponse(data={'name': name}, code=200, message='Excel 已导出')

    @action(methods=['post'], detail=False)  # url 访问127.0.0.1:8080/api/方法名
    def export_current(self, request):
        """
        根据前端传来的搜索内容、页码等条件导出Excel表
        """
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            name = ExportExcel(serializer.data, self.sheet, self.title).write(serializer.data, self.sheet, self.title)
            operation(request, name, self.get_queryset().model._meta.verbose_name_plural, '导出部分')
            return JsonResponse(data={'name': name}, code=200, message='Excel 已导出')
        else:
            return JsonResponse(data={}, code=400, message='Excel 导出错误')


def operation(request, name, meta, action):
    """
    记录操作日志
    操作接口调用
    """
    if 'HTTP_X_FORWARDED_FOR' in request.META:  # 获取ip
        client_ip = request.META['HTTP_X_FORWARDED_FOR']
        client_ip = client_ip.split(",")[0]  # 所以这里是真实的ip
    else:
        client_ip = request.META['REMOTE_ADDR']  # 这里获得代理ip
    OperationModel.objects.create(username=request.user.username, name=request.user.name, mobile=request.user.mobile,
                                  action=action, resource_type=meta, resource=name, ip=client_ip)
